const app = getApp();

Page({
  data: {
    userInfo: null,
    todayAttendance: null,
    monthStats: null,
    locationInfo: null,
    currentDate: '',
    currentTime: '',
    weekDay: '',
    clockInTimeText: '',
    clockOutTimeText: '',
    isClocking: false,
    timeInterval: null
  },

  onLoad() {
    this.setData({
      userInfo: app.globalData.userInfo || wx.getStorageSync('userInfo')
    });
    
    this.updateCurrentTime();
    this.getLocation();
    this.loadTodayAttendance();
    this.loadMonthStats();
    
    // 每秒更新时间
    this.data.timeInterval = setInterval(() => {
      this.updateCurrentTime();
    }, 1000);
  },

  onUnload() {
    if (this.data.timeInterval) {
      clearInterval(this.data.timeInterval);
    }
  },

  // 更新当前时间
  updateCurrentTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const second = String(now.getSeconds()).padStart(2, '0');
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    
    this.setData({
      currentDate: `${year}年${month}月${day}日`,
      currentTime: `${hour}:${minute}:${second}`,
      weekDay: weekDays[now.getDay()]
    });
  },

  // 获取位置
  getLocation() {
    wx.showLoading({ title: '获取位置中...' });
    
    wx.getLocation({
      type: 'gcj02',
      altitude: false,
      success: (res) => {
        wx.hideLoading();
        
        const {longitude, latitude} = res;
        console.log('位置获取成功:', longitude, latitude);
        
        // 使用简单的经纬度显示，不依赖地图API
        this.setData({
          locationInfo: {
            longitude: longitude,
            latitude: latitude,
            address: `经度:${longitude.toFixed(6)}, 纬度:${latitude.toFixed(6)}`,
            location: '打卡位置'
          }
        });
        
        wx.showToast({
          title: '位置获取成功',
          icon: 'success',
          duration: 1500
        });
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取位置失败:', err);
        
        // 检查是否是用户拒绝授权
        if (err.errMsg && err.errMsg.indexOf('auth deny') !== -1) {
          // 用户拒绝了授权，引导去设置
          wx.showModal({
            title: '需要位置权限',
            content: '打卡功能需要获取您的位置信息，请在设置中开启位置权限',
            confirmText: '去设置',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting['scope.userLocation']) {
                      // 授权成功，重新获取位置
                      this.getLocation();
                    }
                  }
                });
              }
            }
          });
        } else {
          // 其他错误
          wx.showModal({
            title: '获取位置失败',
            content: '请确保已开启手机定位服务\n错误信息：' + (err.errMsg || '未知错误'),
            confirmText: '重新获取',
            cancelText: '取消',
            success: (modalRes) => {
              if (modalRes.confirm) {
                this.getLocation();
              }
            }
          });
        }
      }
    });
  },

  // 加载今日考勤
  loadTodayAttendance() {
    const userInfo = this.data.userInfo;
    if (!userInfo) return;
    
    wx.request({
      url: app.globalData.userApiUrl + '/getTodayAttendance',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      data: {
        user_id: userInfo.id
      },
      success: (res) => {
        if (res.data.code === 1) {
          const attendance = res.data.data.attendance;
          
          this.setData({
            todayAttendance: attendance,
            clockInTimeText: attendance && attendance.clock_in_time ? 
              this.formatTime(attendance.clock_in_time) : '',
            clockOutTimeText: attendance && attendance.clock_out_time ? 
              this.formatTime(attendance.clock_out_time) : ''
          });
        }
      }
    });
  },

  // 加载本月统计
  loadMonthStats() {
    const userInfo = this.data.userInfo;
    if (!userInfo) return;
    
    wx.request({
      url: app.globalData.userApiUrl + '/getAttendanceStatistics',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      data: {
        user_id: userInfo.id,
        year_month: new Date().getFullYear() + '-' + String(new Date().getMonth() + 1).padStart(2, '0')
      },
      success: (res) => {
        if (res.data.code === 1) {
          this.setData({
            monthStats: res.data.data.stats
          });
        }
      }
    });
  },

  // 上班打卡
  handleClockIn() {
    const userInfo = this.data.userInfo;
    const locationInfo = this.data.locationInfo;
    
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    if (!locationInfo) {
      wx.showToast({
        title: '正在获取位置信息，请稍候',
        icon: 'none'
      });
      this.getLocation();
      return;
    }
    
    this.setData({ isClocking: true });
    
    wx.request({
      url: app.globalData.userApiUrl + '/clockIn',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      data: {
        user_id: userInfo.id,
        longitude: locationInfo.longitude,
        latitude: locationInfo.latitude,
        address: locationInfo.address,
        location: locationInfo.location,
        device: wx.getSystemInfoSync().model
      },
      success: (res) => {
        this.setData({ isClocking: false });
        
        if (res.data.code === 1) {
          wx.showToast({
            title: res.data.msg,
            icon: res.data.data.is_late ? 'none' : 'success'
          });
          
          this.loadTodayAttendance();
          this.loadMonthStats();
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: () => {
        this.setData({ isClocking: false });
        wx.showToast({
          title: '打卡失败',
          icon: 'none'
        });
      }
    });
  },

  // 下班打卡
  handleClockOut() {
    const userInfo = this.data.userInfo;
    const locationInfo = this.data.locationInfo;
    
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    if (!locationInfo) {
      wx.showToast({
        title: '正在获取位置信息，请稍候',
        icon: 'none'
      });
      this.getLocation();
      return;
    }
    
    this.setData({ isClocking: true });
    
    wx.request({
      url: app.globalData.userApiUrl + '/clockOut',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      data: {
        user_id: userInfo.id,
        longitude: locationInfo.longitude,
        latitude: locationInfo.latitude,
        address: locationInfo.address,
        location: locationInfo.location,
        device: wx.getSystemInfoSync().model
      },
      success: (res) => {
        this.setData({ isClocking: false });
        
        if (res.data.code === 1) {
          wx.showToast({
            title: res.data.msg,
            icon: res.data.data.is_early_leave ? 'none' : 'success'
          });
          
          this.loadTodayAttendance();
          this.loadMonthStats();
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: () => {
        this.setData({ isClocking: false });
        wx.showToast({
          title: '打卡失败',
          icon: 'none'
        });
      }
    });
  },

  // 查看打卡记录
  goToAttendanceList() {
    wx.navigateTo({
      url: '/pages/user-attendance-list/user-attendance-list'
    });
  },

  formatTime(timestamp) {
    const date = new Date(timestamp * 1000);
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    return `${hour}:${minute}:${second}`;
  }
});
